<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\DB;
use think\facade\Request;
use think\facade\Config;
use Firebase\JWT\JWK;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
// use app\middleware\Cors;

class Account
{
    //  protected $middleware = [AuthAdmin::class => ['except'   => ['login','checkAuth'] ]];
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function login(){
        if(Request::isPost()){
            $username=input('param.username');
            $password=input('param.password');
            $account=Config::get('admin');
            if(!isset($account[$username])){
                return json(['code'=>200,'success'=>false,'message'=>'账号不存在']);
            }
            if($account[$username]['password']!=md5($password)){
                return json(['code'=>200,'success'=>false,'message'=>'密码不正确']);

            }
            unset($account[$username]['password']);
            $expires=3600*12;
            $account[$username]['login_at']=time();
            $account[$username]['expires_at']=time()+$expires;
            
            $signature=strtoupper(md5($username.$account[$username]['login_at'].$account[$username]['expires_at']));
            $account[$username]['signature']=$signature;
            $account[$username]['token']=JWT::encode($account[$username],$signature,'HS256');
            // $token=JWT::encode($account[$username],$signature,'HS256');
            // $tokens=['token'=>$token,'signature'=>$signature];
            \think\facade\Cache::store('redis')->set('USER_'.$username.'_'.$signature,$account[$username],$expires);
            // \think\facade\Cache::store('redis')->set('USER_'.$username,$account[$username],$expires);
            return json(['code'=>200,'success'=>true,'message'=>'登录成功','reslut'=>[
                'account'=>$username,'nickname'=>$account[$username]['nickname'],
                'account'=>$account[$username],
                'signature'=>$signature,'token'=>$account[$username]['token']
                ]]);
        }
    }


    public function checkAuth(){
        if(Request::isPost()){
            $account=input('param.account');
            $signature=input('param.signature');
            // $header = Request::header(); // token 合法        
            //     $account = $header['account'];
            //     $signature = $header['signature'];
            $redis=\think\facade\Cache::store('redis')->get('USER_'.$account.'_'.$signature);
            $redis=json_decode(json_encode($redis),true);
            if(!$redis){
                return json(['code'=>201,'success'=>false,'message'=>'签名失效']);
            }
            if($redis['signature']!=$signature){
                return json(['code'=>201,'success'=>false,'message'=>'签名失效']);
            }
            return json(['code'=>200,'success'=>true,'message'=>'验证成功']);  
        }
    }
}